package com.lantosec.hmrp.datacorrection;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lantosec.hmrp.modules.system.entity.SysDept;
import com.lantosec.hmrp.modules.system.service.ISysDeptService;
import com.lantosec.hmrp.modules.workflow.mapper.RepositoryMapper;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 工作流数据修正方法，主要修正act_ge_bytearray表的byte_字段，替换deptId的字段
 *
 * @author lichaowei
 * @date 2020/7/23
 */
@Component
@Log4j2
public class CorrectionService {

    @Autowired
    private RepositoryMapper actRepositoryMapper;
    @Autowired
    private ISysDeptService sysDeptService;

    private List<String> successIdList = new ArrayList<>();
    private List<String> failIdList = new ArrayList<>();
    private List<String> emptyIdList = new ArrayList<>();
    private List<String> errorIdList = new ArrayList<>();

    public void execute() {
        // 查询act_ge_bytearray表所有流程xml文件
        List<Map<String, Object>> mapList = actRepositoryMapper.queryAllEditorSource();

        // 查询所有部门列表对象
        List<SysDept> deptList = sysDeptService.getBaseMapper().selectList(new QueryWrapper<SysDept>().eq(SysDept.ColName.flag.toString(), 0));
        try {
            // 遍历流程的xml文件列表
            for (int i = 0; i < mapList.size(); i++) {
                Map<String, Object> item = mapList.get(i);
                String id = item.get("id_").toString();
                byte[] bytes = (byte[]) item.get("bytes_");
                String xml = new String(bytes, "UTF-8");
                if (StringUtils.isEmpty(id) || StringUtils.isEmpty(xml)) {
                    continue;
                }
                replaceXml(id, xml, 0, deptList);
                // 解析xml文件，替换deptId的值
                //handleXml(id, xml, deptList);
            }

            log.error("成功数量：" + successIdList.size());
            log.error("失败数量：" + failIdList.size());
            log.error("异常数量：" + errorIdList.size());
            log.error("无法查询部门的数量：" + emptyIdList.size());
        } catch (Exception ex) {
        }
    }

    private Boolean replaceXml(String xmlId, String xml, int currentIndex, List<SysDept> deptList) {
        /*if (!xml.contains("Process_202006231650333546")) {
            return false;
        }*/

        int length = xml.length();
        String key = "deptId&#34;:&#34;";
        int startIndex = xml.indexOf(key, currentIndex);
        int endIndex = xml.indexOf("&#34;", startIndex + key.length());
        if (startIndex == -1 || endIndex == -1) {
            if (!errorIdList.contains(xmlId)) {
                errorIdList.add(xmlId);
            }
            return false;
        }
        String oldDeptId = xml.substring(startIndex + key.length(), endIndex);
        String newDeptId = getDeptIdByDeptCode(oldDeptId, deptList);
        if (StringUtils.isEmpty(newDeptId)) {
            log.error("根据部门编码无法查询到部门Id，xmlId：" + xmlId);
            if (!emptyIdList.contains(xmlId)) {
                emptyIdList.add(xmlId);
            }
            return false;
        }
        String startStr = xml.substring(0, startIndex + key.length());
        String endStr = xml.substring(endIndex, length);
        xml = startStr + newDeptId + endStr;
        currentIndex = endIndex;

        int nextIndex = xml.indexOf("deptId&#34;:&#34;", currentIndex);
        if (nextIndex > -1) {
            replaceXml(xmlId, xml, currentIndex, deptList);
        } else {
            // 保存xml文件
            int flag = actRepositoryMapper.updateEditorSourceById(xml, xmlId);
            log.info("保存xml文件：" + flag);
            if (flag > 0) {
                if (!successIdList.contains(xmlId)) {
                    successIdList.add(xmlId);
                }
            } else {
                if (!failIdList.contains(xmlId)) {
                    failIdList.add(xmlId);
                }
            }
            return flag > 0;
        }
        return false;
    }

    private String getDeptIdByDeptCode(String deptCode, List<SysDept> deptList) {
        // 根据deptId配置的值当作code查询对象，然后用deptId替换原来的值
        SysDept sysDept = deptList.stream().filter(a -> a.getDeptCode().equals(deptCode)).
                findFirst().orElse(null);
        if (Objects.isNull(sysDept)) {
            return "";
        }
        return sysDept.getDeptId();
    }
/*

    private Boolean handleXml(String xmlId, String xml, List<SysDept> deptList){
        Boolean flag = false;
        //创建DOM4J解析器对象
        SAXReader saxReader = new SAXReader();
        try {
            InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
            Document document = saxReader.read(is);
            //获取根节点
            Element rootElement = document.getRootElement();
            Element processElement = rootElement.elements().get(0);
            String id = processElement.attributeValue("id");
            // 会签测试2 暂时只用一个Id测试
            if(!"Process_202006231650333546".equals(id)){
                return false;
            }
            List<Element> list = processElement.elements();
            for (int i=0;i<list.size();i++) {
                Element element = list.get(i);
                if ("userTask".equals(element.getName())) {
                    String key = "operator";
                    String operator = element.attributeValue(key);
                    TaskOperatorVO taskOperatorVO = JSON.parseObject(operator, TaskOperatorVO.class);
                    if (taskOperatorVO != null) {
                        TaskOperatorTypeEnum optTypeEnum = TaskOperatorTypeEnum.getByType(taskOperatorVO.getOptType());
                        if (optTypeEnum.equals(TaskOperatorTypeEnum.MANAGER) || optTypeEnum.equals(TaskOperatorTypeEnum.DEPARTMENT)
                                || optTypeEnum.equals(TaskOperatorTypeEnum.DESIGNATION)) {
                            List<UserQueryVO> userList = JSONObject.parseArray(taskOperatorVO.getData(), UserQueryVO.class);
                            if (CollectionUtils.isNotEmpty(userList)) {
                                for (int j = 0; j < userList.size(); j++) {
                                    UserQueryVO user = userList.get(j);
                                    // 根据deptId配置的值当作code查询对象，然后用deptId替换原来的值
                                    SysDept sysDept = deptList.stream().filter(a -> a.getDeptCode().equals(user.getDeptId())).
                                            findFirst().orElse(null);
                                    if (!Objects.isNull(sysDept)) {
                                        String deptId = sysDept.getDeptId();
                                        userList.get(j).setDeptId(deptId);
                                        flag = true;
                                    }
                                }
                                taskOperatorVO.setData(JSON.toJSONString(userList));
                            }
                        }
                        operator = JSON.toJSONString(taskOperatorVO);
                        element.addAttribute(key, operator);
                    }
                }
            }
            xml = document.asXML();
            if (flag) {
                // 保存xml文件
                actRepositoryMapper.updateEditorSourceById(xml, xmlId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
*/

}
